package com.huxiu;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.responses.ProfileResponse;
import com.huxiu.pagers.MyPager;
import com.huxiu.utils.Constants;
import com.huxiu.utils.ErrorResponseException;
import com.huxiu.utils.Global;
import com.huxiu.utils.HttpUtil;
import com.huxiu.utils.LogUtil;
import com.huxiu.utils.Settings;
import com.huxiu.utils.Utils;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * Created by tian on 14-9-20:下午10:14.
 * 第三方授权登录界面
 */
//public class AuthenticatorActivity extends BaseActivity implements WeiboAuthListener, IUiListener {
public class AuthenticatorActivity extends BaseActivity implements IUiListener, WeiboAuthListener {


    public static final int EXISTED_USER_ERROR = 2005;

    private static final String TAG = AuthenticatorActivity.class.getName();

    protected static final String VALUE_HUXIU = "huxiu";

    protected static final String VALUE_SINA = "2";

    protected static final String VALUE_QQ = "3";

    protected static final String KEY_TOKEN = "token";

    protected static final String KEY_OPEN_ID = "openid";

    protected static final String KEY_USERNAME = "username";

    protected static final String KEY_PASSWORD = "password";

    protected static final String KEY_EMAIL = "email";

    protected static final int REQUEST_CODE_BIND_OR_REGISTER = 1;

    protected static final int REQUEST_CODE_COMPLETE_INFO = 2;

    //qcl新浪微博的
    protected AuthInfo mWeiboAuth;

    protected Oauth2AccessToken mAccessToken;

    protected SsoHandler mSsoHandler;

    //qcl腾讯qq的
    protected Tencent mTencent;

    private String errorMsg;

    //qcl微信相关
    public IWXAPI mWechatApi;

    public boolean forBind = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        forBind = getIntent().getBooleanExtra("Bind", false);
        initTencent();
        initWeibo();
        initWeixin();//微信登录成功后的处理在mainactivity中以广播接收者的形式处理
        LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
        lbm.registerReceiver(mReciver, new IntentFilter(Constants.ACTION_WECHAT_LOGIN));//qcl微信的意图过滤器
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
        lbm.unregisterReceiver(mReciver);//qcl解绑广播接收者，节省内存
    }


    //微信回掉
    BroadcastReceiver mReciver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getBooleanExtra("result", false)) {
                String code = intent.getStringExtra("code");
                getWeixinToken(code);
            } else {
                Utils.showToast(R.string.log_in_failed);
            }
        }
    };

    private void initWeixin() {
        mWechatApi = WXAPIFactory.createWXAPI(this, Constants.WECHAT_KEY);
    }

    protected void initTencent() {
        try {
            mTencent = Tencent.createInstance(Constants.TENCENT_APP_ID, getApplicationContext());
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    protected void initWeibo() {
        mWeiboAuth = new AuthInfo(this, Constants.SinaAppKey, Constants.SinaAppRedirectURI,
                Constants.SinaScope);
        mSsoHandler = new SsoHandler(this, mWeiboAuth);
    }

    //qcl获取微信标记
    public void getWeixinToken(final String code) {
        new AsyncTask<Void, Void, Void>() {
            String resultData = null;

            @Override
            protected Void doInBackground(Void... s) {
                HashMap<String, Object> params = new HashMap<String, Object>();
                params.put("appid", Constants.WECHAT_KEY);
                params.put("secret", Constants.WECHAT_SECRECT);
                params.put("code", code);
                params.put("grant_type", "authorization_code");
                resultData = HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token", params);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                String openid = null;
                String token = null;
                if (resultData != null) {
                    try {
                        JSONObject json = new JSONObject(resultData);
                        openid = json.getString("openid");
                        token = json.getString("access_token");
                        if (AuthenticatorActivity.this instanceof LogInActivity) {
                            MyPager.checkBinQQ(token, openid, Constants.LOGIN_TYPE_WXID);
                            finish();
                        } else if (AuthenticatorActivity.this instanceof BindAccountsActivity) {
                            Settings.saveWeixinUid(openid);
                            Map<String, String> params = new LinkedHashMap<>();
                            //                            params.put("token", Global.user.token);
                            params.put("oauth_uid", openid);
                            params.put("oauth_token", token);
                            params.put("oauth_type", "weixin");
                            doBind(params);
                        } else {
                            LogUtil.i("qcl2", "执行了mainactivity绑定方法");
                            MyPager.checkBinQQ(token, openid, Constants.LOGIN_TYPE_WXID);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.execute();
    }


    //qq登录成功
    @Override
    public void onComplete(Object o) {
        JSONObject object = (JSONObject) o;
        try {
            String token = object.optString("access_token");
            String openId = object.optString("openid");

            if (this instanceof LogInActivity) {
                Utils.showToast("登录成功");
                MyPager.checkBinQQ(token, openId, Constants.LOGIN_TYPE_QQID);
                finish();
            } else if (this instanceof BindAccountsActivity) {
                Settings.saveQQUid(openId);
                Map<String, String> params = new LinkedHashMap<>();
                params.put("token", Global.user.token);
                params.put("oauth_uid", openId);
                params.put("oauth_token", token);
                params.put("oauth_type", "qq");
                doBind(params);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(UiError uiError) {
        //                "onError, uiError is " + uiError.errorDetail + ", " + uiError.errorMessage);
        Toast.makeText(this,
                TextUtils.isEmpty(uiError.errorMessage) ? getString(R.string.qq_log_in_failed)
                        : uiError.errorMessage, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCancel() {
        //        Utils.showToast("qq登录取消");
    }

    //新浪微博登录成功后调用的接口
    @Override
    public void onComplete(Bundle bundle) {
        try {
            mAccessToken = Oauth2AccessToken.parseAccessToken(bundle);
            if (mAccessToken.isSessionValid()) {
                String token = mAccessToken.getToken();
                String openId = mAccessToken.getUid();

                //                 Settings.saveWeiboAccessToken(accessToken);

                if (this instanceof LogInActivity) {
                    Utils.showToast("登录成功");
                    MyPager.checkBinQQ(token, openId, Constants.LOGIN_TYPE_SINAID);
                    finish();
                    //                    Map<String, String> params = new LinkedHashMap<>();
                    //                    params.put("act", "login");
                    //                    params.put("login_type", "weibo");
                    //                    params.put("openid", accessToken.getUid());
                    //                    params.put("token", accessToken.getToken());
                    //                    doLogIn(params);
                } else if (this instanceof BindAccountsActivity) {
                    Settings.saveWeiboUid(openId);
                    Map<String, String> params = new LinkedHashMap<>();
                    params.put("token", Global.user.token);
                    params.put("oauth_uid", openId);
                    params.put("oauth_token", token);
                    params.put("oauth_type", "sina");
                    doBind(params);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, getString(R.string.log_in_failed), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onWeiboException(WeiboException e) {
        e.printStackTrace();
        Toast.makeText(this, String.format(getString(R.string.weibo_error), e.getMessage()),
                Toast.LENGTH_LONG).show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == REQUEST_CODE_BIND_OR_REGISTER
                || requestCode == REQUEST_CODE_COMPLETE_INFO) && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
            return;
        }
        // sso 授权回调
        try {
            if (mSsoHandler != null) {
                mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    protected void doBind(Map<String, String> params) {
        String url = NetworkConstants.USER_BINDING_URL;
        GsonRequest<ProfileResponse> request = new GsonRequest<>(url, Request.Method.POST,
                ProfileResponse.class, false, params, new Response.Listener<ProfileResponse>() {
            @Override
            public void onResponse(ProfileResponse response) {
                if (response.isSuccess()) {
                    Utils.showToast("绑定成功");
                    Intent intent = new Intent(Constants.INTENT_USER_BIND_OK);
                    //                    Gson gson = new Gson();
                    //                    String json = gson.toJson(response.data);
                    //                    intent.putExtra("loginJson", json);
                    LocalBroadcastManager.getInstance(APP.getInstance()).sendBroadcast(intent);
                    //                    finish();
                } else {
                    Utils.showToast("qcl绑定失败");
                    Utils.showToast(response.error.message);
                    Settings.clearSinaLogInInfo();
                    Settings.clearQQLogInInfo();
                    Settings.saveWeixinUid("");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Throwable t = error.getCause();
                if (t instanceof ErrorResponseException) {
                    Utils.showToast(error.getMessage());
                    LogUtil.i("qcl2", "绑定失败时清空已经存储的信息");
                    Settings.clearSinaLogInInfo();
                    Settings.clearQQLogInInfo();
                    Settings.saveWeixinUid("");
                } else {
                    Utils.showToast(R.string.generic_failure);
                }
            }
        });
        mQueue.add(request);
    }

    protected void updateUI() {
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }
}
